package com.caigou.modules.forum.ui.publish.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.caigou.comm.base.bean.PrizeBallBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.ContestBallItem2Adapter
import com.caigou.modules.forum.databinding.FragmentContestTeMaBinding
import com.caigou.modules.forum.viewmodel.PublishViewModel
import dagger.hilt.android.AndroidEntryPoint
import org.json.JSONArray
import org.json.JSONObject

/**
 * @author #Suyghur.
 * Created on 2021/12/26
 */
@AndroidEntryPoint
class TeMaFragment : BaseFragment() {

    private var _binding: FragmentContestTeMaBinding? = null
    private val binding get() = _binding!!

    private val publishViewModel: PublishViewModel by viewModels()

    private lateinit var ma12Adapter: ContestBallItem2Adapter
    private lateinit var ma8Adapter: ContestBallItem2Adapter
    private lateinit var ma4Adapter: ContestBallItem2Adapter
    private lateinit var ma1Adapter: ContestBallItem2Adapter

    private var ma12CheckNum = 0
    private var ma8CheckNum = 0
    private var ma4CheckNum = 0
    private var ma1CheckNum = 0

    private var ma12Balls = mutableListOf<PrizeBallBean>()
    private var ma8Balls = mutableListOf<PrizeBallBean>()
    private var ma4Balls = mutableListOf<PrizeBallBean>()
    private var ma1Balls = mutableListOf<PrizeBallBean>()

    private val prizeBalls = mutableListOf<PrizeBallBean>()

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentContestTeMaBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        handle12MaView()
        handle8MaView()
        handle4MaView()
        handle1MaView()

        binding.contestTeMaBtn8maAdd.setOnClickListener {
            if (ma12CheckNum < 12) {
                showToast("请选择12码")
                return@setOnClickListener
            }
            binding.contestTeMaCv8ma.visibility = View.VISIBLE
            binding.contestTeMaBtn4maAdd.visibility = View.VISIBLE
            for (pos in 0..48) {
                ma12Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isClickable = false
                }
            }
            ma8Adapter.setList(ma12Balls)
            it.visibility = View.GONE
        }
        binding.contestTeMaIv8maClear.setOnClickListener {
            binding.contestTeMaCv8ma.visibility = View.GONE
            binding.contestTeMaBtn4maAdd.visibility = View.GONE
            binding.contestTeMaBtn8maAdd.visibility = View.VISIBLE
            for (pos in 0..48) {
                ma12Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isClickable = true
                }
            }
            for (pos in 0..11) {
                ma8Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isChecked = false
                }
            }
            ma8Balls.clear()
            ma8Adapter.setList(mutableListOf())
        }

        binding.contestTeMaBtn4maAdd.setOnClickListener {
            if (ma8CheckNum < 8) {
                showToast("请选择8码")
                return@setOnClickListener
            }
            binding.contestTeMaIv8maClear.visibility = View.GONE
            binding.contestTeMaBtn1maAdd.visibility = View.VISIBLE
            binding.contestTeMaCv4ma.visibility = View.VISIBLE
            for (pos in 0..11) {
                ma8Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isClickable = false
                }
            }
            ma4Adapter.setList(ma8Balls)
            it.visibility = View.GONE
        }
        binding.contestTeMaIv4maClear.setOnClickListener {
            binding.contestTeMaIv8maClear.visibility = View.VISIBLE
            binding.contestTeMaCv4ma.visibility = View.GONE
            binding.contestTeMaBtn1maAdd.visibility = View.GONE
            binding.contestTeMaBtn4maAdd.visibility = View.VISIBLE
            for (pos in 0..11) {
                ma8Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isClickable = true
                }
            }
            for (pos in 0..7) {
                ma4Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isChecked = false
                }
            }
            ma4Balls.clear()
            ma4Adapter.setList(mutableListOf())
        }

        binding.contestTeMaBtn1maAdd.setOnClickListener {
            if (ma4CheckNum < 4) {
                showToast("请选择4码")
                return@setOnClickListener
            }
            binding.contestTeMaIv4maClear.visibility = View.GONE
            binding.contestTeMaCv1ma.visibility = View.VISIBLE
            for (pos in 0..7) {
                ma4Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isClickable = false
                }
            }
            ma1Adapter.setList(ma4Balls)
            it.visibility = View.GONE
        }
        binding.contestTeMaIv1maClear.setOnClickListener {
            binding.contestTeMaIv4maClear.visibility = View.VISIBLE
            binding.contestTeMaCv1ma.visibility = View.GONE
            binding.contestTeMaBtn1maAdd.visibility = View.VISIBLE
            for (pos in 0..7) {
                ma4Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isClickable = true
                }
            }
            for (pos in 0..3) {
                ma1Adapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isChecked = false
                }
            }
            ma1Balls.clear()
            ma1Adapter.setList(mutableListOf())
        }

        binding.contestTeMaBtnSubmit.setOnClickListener {
            val ob = JSONObject()
            val jsonArray = JSONArray()

            if (ma12Balls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val content = StringBuilder()

                for (index in 0 until ma12Balls.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(ma12Balls[index].number).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestTeMaTv12maContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 7)
                jsonArray.put(jsonObject)
            }

            if (ma8Balls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val content = StringBuilder()

                for (index in 0 until ma8Balls.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(ma8Balls[index].number).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestTeMaTv8maContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 6)
                jsonArray.put(jsonObject)
            }

            if (ma4Balls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val content = StringBuilder()

                for (index in 0 until ma4Balls.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(ma4Balls[index].number).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestTeMaTv4maContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 5)
                jsonArray.put(jsonObject)
            }

            if (ma1Balls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val content = StringBuilder()

                for (index in 0 until ma1Balls.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(ma1Balls[index].number).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestTeMaTv1maContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 4)
                jsonArray.put(jsonObject)
            }

            ob.put("dareContent", jsonArray.toString())
            ob.put("dareType", 2)
            LiveDataBus.get().with(BusKey.DARE_CONTENT_FILL, String::class.java).value = ob.toString()
            requireActivity().finish()
        }
    }

    override fun lazyLoad() {
        publishViewModel.getPrizeBallList()
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(publishViewModel.prizeBallListLiveData, ::handleGetPrizeBallList)
    }

    private fun handleGetPrizeBallList(result: Resource<MutableList<PrizeBallBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    prizeBalls.addAll(this)
                    ma12Adapter.notifyDataSetChanged()
                }
            }
        }
    }

    private fun handle12MaView() {
        ma12Adapter = ContestBallItem2Adapter(prizeBalls, object : ContestBallItem2Adapter.BallItemCallback {
            override fun onBallCheckedChange(buttonView: CompoundButton, isChecked: Boolean, item: PrizeBallBean) {
                if (isChecked) {
                    if (ma12CheckNum < 12) {
                        ma12CheckNum++
                        ma12Balls.add(item)
                        change12MaContentTxt()
                    } else {
                        showToast("最多选择12个")
                        buttonView.isChecked = false
                    }
                } else {
                    ma12CheckNum--
                    ma12Balls.remove(item)
                    change12MaContentTxt()
                }
            }
        })

        binding.contestTeMaRecyclerView12ma.run {
            layoutManager = GridLayoutManager(requireActivity(), 7)
            adapter = ma12Adapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }

    private fun handle8MaView() {
        ma8Adapter = ContestBallItem2Adapter(mutableListOf(), object : ContestBallItem2Adapter.BallItemCallback {
            override fun onBallCheckedChange(buttonView: CompoundButton, isChecked: Boolean, item: PrizeBallBean) {
                if (isChecked) {
                    if (ma8CheckNum < 8) {
                        ma8CheckNum++
                        ma8Balls.add(item)
                        change8MaContentTxt()
                    } else {
                        showToast("最多选择8个")
                        buttonView.isChecked = false
                    }
                } else {
                    ma8CheckNum--
                    ma8Balls.remove(item)
                    change8MaContentTxt()
                }
            }
        })

        binding.contestTeMaRecyclerView8ma.run {
            layoutManager = GridLayoutManager(requireActivity(), 7)
            adapter = ma8Adapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }


    private fun handle4MaView() {
        ma4Adapter = ContestBallItem2Adapter(mutableListOf(), object : ContestBallItem2Adapter.BallItemCallback {
            override fun onBallCheckedChange(buttonView: CompoundButton, isChecked: Boolean, item: PrizeBallBean) {
                if (isChecked) {
                    if (ma4CheckNum < 4) {
                        ma4CheckNum++
                        ma4Balls.add(item)
                        change4MaContentTxt()
                    } else {
                        showToast("最多选择4个")
                        buttonView.isChecked = false
                    }
                } else {
                    ma4CheckNum--
                    ma4Balls.remove(item)
                    change4MaContentTxt()
                }
            }
        })

        binding.contestTeMaRecyclerView4ma.run {
            layoutManager = GridLayoutManager(requireActivity(), 7)
            adapter = ma4Adapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }

    private fun handle1MaView() {
        ma1Adapter = ContestBallItem2Adapter(mutableListOf(), object : ContestBallItem2Adapter.BallItemCallback {
            override fun onBallCheckedChange(buttonView: CompoundButton, isChecked: Boolean, item: PrizeBallBean) {
                if (isChecked) {
                    if (ma1CheckNum < 1) {
                        ma1CheckNum++
                        ma1Balls.add(item)
                        change1MaContentTxt()
                    } else {
                        showToast("最多选择1个")
                        buttonView.isChecked = false
                    }
                } else {
                    ma1CheckNum--
                    ma1Balls.remove(item)
                    change1MaContentTxt()
                }
            }
        })

        binding.contestTeMaRecyclerView1ma.run {
            layoutManager = GridLayoutManager(requireActivity(), 7)
            adapter = ma1Adapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }


    private fun change12MaContentTxt() {
        if (ma12Balls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until ma12Balls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(ma12Balls[index].number).append("-")
            }
            binding.contestTeMaTv12maContent.text = content
        }
    }

    private fun change8MaContentTxt() {
        if (ma8Balls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until ma8Balls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(ma8Balls[index].number).append("-")
            }
            binding.contestTeMaTv8maContent.text = content
        }
    }

    private fun change4MaContentTxt() {
        if (ma4Balls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until ma4Balls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(ma4Balls[index].number).append("-")
            }
            binding.contestTeMaTv4maContent.text = content
        }
    }

    private fun change1MaContentTxt() {
        if (ma1Balls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until ma1Balls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(ma1Balls[index].number).append("-")
            }
            binding.contestTeMaTv1maContent.text = content
        }
    }
}